﻿// golobal variables
var db;
var validator;

// Onloadイベント
$(document).ready(function()
{
    // Open database
    db = openDatabase("todolist", "1.0", "To Do List Database", 100 * 1024);
    db.transaction(function(transaction)
    {
        transaction.executeSql("CREATE TABLE IF NOT EXISTS task( name TEXT NOT NULL, description TEXT, due DATETIME);");
    });

    // validate form
    validator = $("#taskentry").validate({ debug: true });
    $("input[name='editname']").rules("add", { required: true, messages: { required: "Please enter task name"} });
    $("input[name='editdue']").rules("add", { required: true, messages: { required: "Please enter due date" }, date: true });
});

// エラーチェック
function hasError()
{
    // check whether has errors or not
    var errors = validator.numberOfInvalids();
    return errors > 0;
}

// 画面を初期化する
function Clear()
{
    $("#taskname").val('');
    $("#taskdesc").val('');
    $("#taskdue").val('');
}

// タスクを登録する
function onSave()
{
    // submit form to check invalid items
    $("#taskentry").submit();

    // validate form
    if (hasError()) {
        return;
    }

    // insert item to database
    var taskname = "'" + $("#taskname").val() + "'";
    var taskdesc = "'" + $("#taskdesc").val() + "'";
    var taskdue = "'" + $("#taskdue").val() + "'";

    CreateTask(db, taskname, taskdesc, taskdue);
}

// タスクを作成する
function CreateTask(t, taskname, taskdesc, taskdue)
{
    t.transaction(function(transaction)
    {
        transaction.executeSql("INSERT INTO task(name, description , due) VALUES(" + taskname + ", " + taskdesc + ", " + taskdue + ");");
        alert("Insert completed!");
        Clear();
    });
}